using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Diagnostics;
namespace Test {
	static class Program {
		static void MainX() {
			Nod nod=new Nod(File.ReadAllText("test1.txt"));
			//Nod nod=new Nod("<a>das<a>test</a></a>");
			//string[] imgs=nod.Singles("<img");
			System.Diagnostics.Stopwatch sw=System.Diagnostics.Stopwatch.StartNew();
			string[] div1=nod.Doubles("<div class=\"title\">");
			string[] anc1=nod.Doubles("<a");
			Console.WriteLine(sw.Elapsed);
		}
	}
	class Nod {
		public Nod(string content) { _content=content; }
		string _content;
		public string[] Regex(string regex) {
			Regex rx=new Regex(regex,RegexOptions.Singleline);
			MatchCollection mc=rx.Matches(_content);
			string[] ret=new string[mc.Count];
			int cnt=0;
			foreach(Match mac in mc)
				ret[cnt++]=mac.Groups[mac.Groups.Count-1].Value;
			return ret;
		}
		public string[] Doubles(string pattern) {
			//int next=0;
			List<string> ret=new List<string>();
			Regex reg=new Regex(pattern);
			foreach(Match mat in reg.Matches(_content))
				ret.Add(Double(mat.Value,mat.Index));
			return ret.ToArray();
		}
		private string[] oDoubles(string pattern) {
			int next=0;
			List<string> ret=new List<string>();
			do
			{
				next=_content.IndexOf(pattern,next);
				if(next<0)
					break;
				//Console.WriteLine(_content.Substring(next));
				string itm=Double(pattern,next);
				ret.Add(itm);
				next++;
			}
			while(next>0);
			return ret.ToArray();
		}
		//public string Double(string pattern) {
		//  return Double(pattern,0);
		//}
		private string Double(string pattern,int istart) {
			int lvl=0;
			string part=pattern.Replace("<","").Replace(">"," ").Split(' ')[0];
			int ix0=istart;
			int startpos=_content.IndexOf(pattern,ix0);
			do
			{
				int ixs=_content.IndexOf("<"+part,ix0);
				if(ixs==-1)
					ixs=int.MaxValue;
				int ixe=_content.IndexOf("</"+part+">",ix0);
				if(ixe==-1)
					ixe=int.MaxValue;
				else if(ixs<ixe)
					lvl++;
				else if(ixs>ixe)
					lvl--;
				else
					return "!";
				if(lvl==0)
					return _content.Substring(startpos,ixe-startpos+part.Length+3);
				ix0=Math.Min(ixs,ixe)+1;
			} while(lvl>0&&lvl<20);
			return "";
		}
	}
}
